import React, { Component } from 'react'
import {
	StyleSheet, Text, View, TouchableOpacity, Image, FlatList, ScrollView, Alert
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { ApproveRefuseModal } from '../../order/approve/details/modals/refuse';
import ToastUtil from '../../../utils/toast';
import { CommonDialog } from '../../../components/common/Dialog';

const scale = GLOBAL.SCALE;
const TAB_LIST = [
	{
		name: '通知单商品',
		id: 0, // TODO
	}, {
		name: '车船信息',
		id: 1, // TODO
	}
]
export class StockApproveDetailPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		const { title } = navigation.state.params;
		return {
			headerTitle: title + '详情',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerStyle: {  // 头部整体样式 
				elevation: 0,
				borderBottomWidth: 0,
				backgroundColor: style.color.themeColor
			},
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props)
		this.state = {
			status: 'data',
			curId: 0,
			detail: null,
			refuseModalVisible: false,
			modalVisible: false,
			modalTitle: '',
			alertRemark: ''
		}

		this.pageParams = this.props.navigation.state.params
	}

	componentWillMount() {
		this.initPage();
	}

	async	initPage() {
		this.setState({
			status: 'loading'
		})
		const api = this.pageParams.id == '1' ? API.GET_SALE_DETAIL : API.GET_PURCHASE_DETAIL;
		const response = await HTTP.POST(API_GENERATE(api), { businessKey: this.pageParams.businessKey, corpId: this.pageParams.choice.corpId });

		if (response) {
			this.setState({
				detail: response,
				status: 'data'
			})
		} else {
			this.setState({
				status: 'error'
			})
		}
	}

	changeTab(item) {
		this.setState({
			curId: item.id
		})
	}

	async _audit() {
		let { detail } = this.state;
		const { createName } = detail || {};
		if (this.requesting) return;
		this.setState({ refuseModalVisible: false, loaded: true });
		this.requesting = true;
		const api = this.pageParams.id == '1' ? API.GET_SALE_AUDIT_NOTICE : API.GET_PURCHASE_AUDIT_NOTICE;
		const responseData = await HTTP.POST(API_GENERATE(api), {
			businessKey: this.businessKey,
			auditResult: this.isAgreed,
			remark: this.remark, // 填写
		});
		this.setState({ loaded: false });
		if (responseData) {
			ToastUtil.showSuccess(this.isAgreed ? '审批成功' : '驳回成功').then(() => {
				this.requesting = false;
				this.props.navigation.state.params.callback();
				if (this.isAgreed) {
					this.props.navigation.navigate('PushEail', { noticeId: this.businessKey, inOutFlag: this.pageParams.id, createName: createName || null });
				} else {
					this.props.navigation.navigate('StockApproveListPage');
				}
			})
		} else {
			this.requesting = false;
		}
	}

	_pass() {
		this.isAgreed = 1;
		this.remark = '';
		this.setState({
			refuseModalVisible: true
		})
	}

	_refuse() {
		this.isAgreed = 0;
		this.remark = '';
		this.setState({
			refuseModalVisible: true
		})
	}

	// 查看备注
	showRemark = (index, alertRemark) => {
		this.setState({
			modalVisible: true,
			modalTitle: index ? '仓库' : '备注',
			alertRemark
		})
	}

	_renderTabWrap() {
		return (
			<View style={styles.bottomListTabsView}>
				{
					TAB_LIST.map((item, index) => {
						return (
							<TouchableOpacity key={index} activeOpacity={1} onPress={() => { this.changeTab(item) }}
								style={[styles.bottomListTabs, this.state.curId == item.id ? styles.bottomListTabsBorder : null]}>
								<Text style={styles.bottomListTabsValue}>{item.name}</Text>
							</TouchableOpacity>
						)
					})
				}
			</View>
		)
	}

	_renderTabList() {
		const { curId, detail } = this.state;
		const { tools, items, itemTOS } = detail || {};
		const proData = this.pageParams.id == '1' ? items : itemTOS;

		if (curId) {
			//车船信息
			return tools && tools.length ? this._renderToolsInfo(tools) : this._renderEmpty('暂无数据');
		} else {
			//通知单商品
			return proData && proData.length ? this._renderProductInfo(proData) : this._renderEmpty('暂无数据');
		}
	}

	_renderProductInfo(data) {
		return (
			<View style={styles.tabList}>
				{
					data.map((item, index) => {
						const { planId, inStockBatchNo, procurementBatchNo, goodsName, noticeQuantity } = item;
						return (
							<View key={index} style={styles.tabListView}>
								<View style={styles.billNumWrap}>
									<Text style={styles.topInfoValue}>{goodsName} </Text>
								</View>

								<View style={styles.billInfoWrap}>
									<View style={{ flexDirection: 'row', alignItems: 'center' }}>
										<Text style={styles.commonTitle}>通知量（吨）</Text>
										<Text style={styles.commonTitle}>采购批次号</Text>
										<Text style={styles.commonTitle}>入库批次号</Text>
									</View>
									<View style={{ flexDirection: 'row', alignItems: 'flex-start' }}>
										<Text style={styles.commonText}>{(noticeQuantity || 0).toFixed(3)}</Text>
										<Text style={styles.commonText}>{procurementBatchNo || '-'}</Text>
										<Text style={styles.commonText}>{inStockBatchNo || '-'}</Text>
									</View>
								</View>

								<View style={styles.billInfoWrap}>
									<Text style={styles.commonTitle}>运输委托子项号</Text>
									<Text style={styles.commonText}>{planId || '-'}</Text>
								</View>
							</View>
						)
					})
				}
			</View>
		)
	}

	_renderToolsInfo(data) {
		return (
			<View style={styles.tabList}>
				{
					data.map((item, index) => {
						const { dispatchNo, transToolName, trailerNo, sheetQuantity } = item;
						return (
							<View key={index} style={styles.tabListView}>
								<View style={styles.billNumWrap}>
									<Text style={styles.commonTitle}>调度号</Text>
									<Text style={[styles.commonTitle, { flex: 1 }]}>{dispatchNo || '-'} </Text>
								</View>

								<View style={styles.billInfoWrap}>
									<View style={{ flexDirection: 'row', alignItems: 'center' }}>
										<Text style={styles.commonTitle}>运量（吨）</Text>
										<Text style={styles.commonTitle}>车船号</Text>
										<Text style={styles.commonTitle}>挂车号</Text>
									</View>
									<View style={{ flexDirection: 'row', alignItems: 'flex-start' }}>
										<Text style={styles.commonText}>{(sheetQuantity || 0).toFixed(3)}</Text>
										<Text style={styles.commonText}>{transToolName || '-'}</Text>
										<Text style={styles.commonText}>{trailerNo || '-'}</Text>
									</View>
								</View>
							</View>
						)
					})
				}
			</View>
		)
	}

	_renderEmpty(tip) {
		return (
			<View style={styles.billNumWrap}>
				<Text style={styles.topInfoValue}>{tip} </Text>
			</View>
		)
	}

	render() {
		let { status, detail, curId, modalVisible, modalTitle, alertRemark } = this.state;
		const { supplierName, companyName, createTime, createName, orderId, noticeId, noticeQuantity, expectExeDate, warehouseName,
			salesManName, bizTeamName, organName, deliveryTypeName, isDirectSellingName, receivingAddress, settlementPartyName,
			freeDays, remark, shipmentsAddress, outStockStartDate, outStockEndDate, tools, itemTOS, items, warehouseId } = detail || {};
		return (
			<ScrollView style={styles.container}>
				<View style={styles.topContainer}>
					<View style={styles.topInfoView}>
						<View style={styles.topInfoTextView}>
							<Text style={[styles.topInfoLabel, { marginBottom: 12 * scale }]}>{this.pageParams.id == '1' ? '出' : '入'}库通知单号：</Text>
							<Text style={[styles.topInfoValue, { marginBottom: 12 * scale }]}>{noticeId || '-'}</Text>
						</View>
						<View style={styles.topInfoTextView}>
							<Text style={styles.topInfoLabel}>订单号：</Text>
							<Text style={styles.topInfoValue}>{orderId || '-'}</Text>
						</View>
					</View>
					<View style={styles.buttonBox}>
						<TouchableOpacity style={styles.buttonPass} activeOpacity={1} onPress={() => {
							this.businessKey = noticeId;
							this._pass();
						}}>
							<Text style={styles.buttonPassText}>通过</Text>
						</TouchableOpacity>
						<TouchableOpacity style={styles.buttonRefuse} activeOpacity={1} onPress={() => {
							this.businessKey = noticeId;
							this._refuse();
						}}>
							<Text style={styles.buttonRefuseText}>驳回</Text>
						</TouchableOpacity>
					</View>
				</View>

				<View style={styles.billInfoWrap}>
					<View style={styles.commonRowLabel}>
						<Text style={styles.commonTitle}>{this.pageParams.id == '1' ? '客户名称' : '供应商'}</Text>
						<Text style={styles.commonTitle}>通知量（吨）</Text>
						<Text style={styles.commonTitle}>{this.pageParams.id == '1' ? '出货日期' : '收货日期'}</Text>
					</View>
					<View style={styles.commonRowValue}>
						<Text style={styles.commonText}>{(this.pageParams.id == '1' ? companyName : supplierName) || '-'}</Text>
						<Text style={styles.commonText}>{(noticeQuantity || 0).toFixed(3)}</Text>
						{
							this.pageParams.id == '1' ?
								<View style={{ flex: 1 }}>
									<Text style={styles.commonText}>
										{outStockStartDate ? outStockStartDate.substring(0, 10) : null}
									</Text>
									{outStockEndDate ? <Text style={styles.commonText}>{outStockEndDate.substring(0, 10)}</Text> : null}
								</View>
								:
								<Text style={styles.commonText}>{(expectExeDate || '-').substring(0, 10)}</Text>
						}
					</View>
				</View>
				<View style={styles.billInfoWrap}>
					<View style={styles.commonRowLabel}>
						<Text style={styles.commonTitle}>{this.pageParams.id == '1' ? '提货费发生方' : '交货方式'}</Text>
						<Text style={styles.commonTitle}>免仓期</Text>
						<Text style={styles.commonTitle}>是否直销</Text>
					</View>
					<View style={styles.commonRowValue}>
						<Text style={styles.commonText}>{this.pageParams.id == '1' ? (settlementPartyName || '-') : (deliveryTypeName || '-')}</Text>
						<Text style={styles.commonText}>{freeDays || 0}</Text>
						<Text style={styles.commonText}>{isDirectSellingName}</Text>
					</View>
				</View>
				{
					this.pageParams.id == '1' ?
						<View style={styles.billInfoWrap}>
							<View style={styles.commonRowLabel}>
								<Text style={styles.commonTitle}>交货方式</Text>
								<Text style={styles.commonTitle}>备注</Text>
								<Text style={styles.commonTitle}>发货仓库</Text>
							</View>
							<View style={styles.commonRowValue}>
								<Text style={styles.commonText}>{deliveryTypeName || '-'}</Text>
								<Text style={[styles.commonText, { color: style.color.themeColor }]} onPress={() => { this.showRemark(0, (remark || '无')); }}>
									【查看备注】
								</Text>
								{
									warehouseId == 'V' ? <Text style={[styles.commonText, { color: style.color.themeColor }]} onPress={() => { this.showRemark(1, warehouseName + shipmentsAddress); }}>【虚拟仓库】</Text> :
										<Text style={[styles.commonText, { color: style.color.themeColor }]} onPress={() => { this.showRemark(1, warehouseName + shipmentsAddress); }}>{warehouseName}</Text>
								}
							</View>
						</View>
						:
						<View style={styles.billInfoWrap}>
							<View style={styles.commonRowLabel}>
								<Text style={styles.commonTitle}>备注</Text>
								<Text style={styles.commonTitle}>收货仓库</Text>
								<Text style={styles.commonTitle}>制单人</Text>
							</View>
							<View style={styles.commonRowValue}>
								<Text style={[styles.commonText, { color: style.color.themeColor }]} onPress={() => { this.showRemark(0, (remark || '无')); }}>【查看备注】
								</Text>
								<Text style={[styles.commonText, { color: style.color.themeColor }]} onPress={() => { this.showRemark(1, warehouseName + '：' + receivingAddress); }}>【{warehouseName || '仓库'}】</Text>
								<Text style={styles.commonText}>{createName || '-'}</Text>
							</View>
						</View>
				}
				<View style={styles.billInfoWrap}>
					<View style={styles.commonRowLabel}>
						{this.pageParams.id == '1' ? <Text style={styles.commonTitle}>制单人</Text> : null}
						<Text style={styles.commonTitle}>制单日期</Text>
						<Text style={[styles.commonTitle, this.pageParams.id !== '1' ? { flex: 3 } : { flex: 1 }]}>业务员（部门）</Text>
					</View>
					<View style={styles.commonRowValue}>
						{this.pageParams.id == '1' ? <Text style={styles.commonText}>{createName || '-'}</Text> : null}
						<Text style={styles.commonText}>{(createTime || '-').substring(0, 10)}</Text>
						<Text style={[styles.commonText, this.pageParams.id !== '1' ? { flex: 2 } : { flex: 1 }]}>
							{salesManName || bizTeamName || organName ? `${salesManName || '-'} | ${bizTeamName || '--'} | ${organName || '-'}` : '--'}
						</Text>
					</View>
				</View>

				<View style={styles.bottomListView}>
					{this._renderTabWrap()}
					{detail ? this._renderTabList() : null}
				</View>

				{
					status != 'data' ? (<View style={{ position: 'absolute', height: GLOBAL.SCREEN_HEIGHT - 80, width: GLOBAL.SCREEN_WIDTH, top: 0 }}>
						<PageStatusIndex status={status} />
					</View>) : null
				}

				<CommonDialog modalVisible={modalVisible} title={modalTitle} text={alertRemark} onClosePress={() => { this.setState({ modalVisible: false }) }} />

				<ApproveRefuseModal
					titleText={'审批意见'}
					placeholderText={this.isAgreed ? '请输入同意原因' : null}
					propsDefaultValue={this.isAgreed ? '审批同意' : '审批驳回'}
					visible={this.state.refuseModalVisible}
					btnPress={(remark) => {
						this.remark = remark;
						this._audit();
					}}
					bgPress={() => {
						this.setState({
							refuseModalVisible: false,
						});
					}} />
			</ScrollView>
		)
	}

}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	buttonPass: {
		width: 60 * scale,
		backgroundColor: style.color.themeColor,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		marginRight: 10 * scale,
		borderRadius: 16 * scale,
		borderColor: style.color.themeColor,
		borderWidth: 1,
	},
	buttonPassText: {
		color: '#fff',
		fontSize: 12 * scale,
		fontWeight: '700',
		textAlign: 'center'
	},
	buttonRefuse: {
		width: 60 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		borderRadius: 16 * scale,
		borderColor: style.color.themeColor,
		borderWidth: 1,
		marginRight: 14 * scale,
	},
	buttonRefuseText: {
		color: style.color.themeColor,
		fontSize: 12 * scale,
		fontWeight: '700',
		textAlign: 'center'
	},
	buttonBox: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'flex-end',
	},
	topContainer: {
		flexDirection: 'row',
		paddingTop: 18 * scale,
	},
	topInfoView: {
		flex: 1,
		paddingLeft: 14 * scale
	},
	topInfoTextView: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
	},
	topInfoLabel: {
		color: '#080808',
		fontSize: 12 * scale,
		textAlign: 'right',
	},
	topInfoValue: {
		color: '#080808',
		fontSize: 12 * scale,
		fontWeight: '700',
		flexWrap: 'wrap'
	},
	billInfoWrap: {
		flexDirection: 'column',
		alignItems: 'flex-start',
		justifyContent: 'flex-start',
		paddingLeft: 14 * scale,
		paddingRight: 14 * scale,
		paddingTop: 20 * scale,
	},
	commonTitle: {
		flex: 1,
		color: '#030303',
		fontSize: 10 * scale,
		minWidth: 64 * scale,
	},
	commonText: {
		// width: 108 * scale,
		flex: 1,
		fontSize: 10 * scale,
		color: '#0C0C0D',
		fontWeight: '800',
		paddingTop: 8 * scale
	},
	commonRowLabel: {
		flexDirection: 'row',
		alignItems: 'center'
	},
	commonRowValue: {
		flexDirection: 'row',
		alignItems: 'flex-start'
	},
	bottomListView: {
		marginTop: 18 * scale,
		padding: 14 * scale
	},
	bottomListTabsView: {
		flexDirection: 'row',
		alignItems: 'center',
		borderStyle: 'solid',
		borderBottomColor: '#E3E7F0',
		borderBottomWidth: 1 * scale,
	},
	bottomListTabs: {
		marginRight: 24 * scale,
		paddingBottom: 6 * scale
	},
	bottomListTabsBorder: {
		borderStyle: 'solid',
		borderBottomColor: '#0A0A0A',
		borderBottomWidth: 3 * scale,
	},
	bottomListTabsValue: {
		fontSize: 14 * scale,
		color: '#000',
		fontWeight: '800',
	},
	billNumWrap: {
		flexDirection: 'row',
		alignItems: 'center',
		paddingLeft: 14 * scale,
		paddingRight: 14 * scale,
		paddingTop: 16 * scale,
		height: 40 * scale
	},
	tabList: {
		marginTop: 20 * scale
	},
	tabListView: {
		backgroundColor: '#fff',
		borderRadius: 4 * scale,
		paddingBottom: 10 * scale
	}
})